package com.jack006.admin.controller;

import com.jack006.admin.service.CategoryService;
import com.jack006.api.BaseController;
import com.jack006.api.controller.admin.CategoryMngControllerApi;
import com.jack006.grace.result.GraceJSONResult;
import com.jack006.grace.result.ResponseStatusEnum;
import com.jack006.pojo.Category;
import com.jack006.pojo.bo.SaveCategoryBO;
import com.jack006.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @Classname CategoryMngController
 * @Description 文章分类控制类
 * @Date 2021-07-03 14:38
 * @Created by jack
 */
@RestController
public class CategoryMngController extends BaseController implements CategoryMngControllerApi {

    final static Logger logger = LoggerFactory.getLogger(FriendLinkController.class);

    @Autowired
    private CategoryService categoryService;

    @Override
    public GraceJSONResult saveOrUpdateCategory(@Valid SaveCategoryBO saveCategoryBO) {


        Category newCat = new Category();
        BeanUtils.copyProperties(saveCategoryBO,newCat);

        // id 为空新增，不为空修改
        if (saveCategoryBO.getId() == null) {
            boolean isExist = categoryService.queryCatIsExist(newCat.getName(),null);
            if (!isExist) {
                // 新增到数据库
                categoryService.createCategory(newCat);
            } else {
                return GraceJSONResult.errorCustom(ResponseStatusEnum.CATEGORY_EXIST_ERROR);
            }
        } else {
            // 查询修改的分类名称不能重复存在
            boolean isExist = categoryService.queryCatIsExist(newCat.getName(), saveCategoryBO.getOldName());
            if (!isExist) {
                // 修改到数据库
                categoryService.modifyCategory(newCat);
            } else {
                return GraceJSONResult.errorCustom(ResponseStatusEnum.CATEGORY_EXIST_ERROR);
            }
        }

        return GraceJSONResult.ok();
    }

    @Override
    public GraceJSONResult getCatList() {
        List<Category> categoryList =  categoryService.queryCatList();
        return GraceJSONResult.ok(categoryList);
    }

    @Override
    public GraceJSONResult getCats() {

        // 1、先从 redis 中查询，如果有则返回，如果没有，则直接返回return
        String allCatJson = redisOperator.get(REDIS_ALL_CATEGORY);
        List<Category> categoryList;
        if (StringUtils.isBlank(allCatJson)) {
            categoryList =  categoryService.queryCatList();
            redisOperator.set(REDIS_ALL_CATEGORY,JsonUtils.objectToJson(categoryList));
        } else {
            categoryList = JsonUtils.jsonToList(allCatJson,Category.class);
        }
        return GraceJSONResult.ok(categoryList);
    }
}
